package main

import (
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"godco/internal/config"
	"godco/internal/handler"
	"godco/internal/svc"
	"net/http"
	"os"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/godco-api.yaml", "the config file")

// 自定义文件系统，禁用目录访问
type noDirFileSystem struct {
	fs http.FileSystem
}

func (n noDirFileSystem) Open(name string) (http.File, error) {
	f, err := n.fs.Open(name)
	if err != nil {
		return nil, err
	}

	// 检查是否为目录
	stat, err := f.Stat()
	if err != nil {
		return nil, err
	}
	if stat.IsDir() {
		fmt.Println("目录")
		return nil, os.ErrNotExist // 触发404
	}
	return f, nil
}

func InitRedis(cfg config.RedisConf) *redis.Redis {
	redisConf := redis.RedisConf{
		Host: cfg.Host,
		Pass: cfg.Pass,
		Type: cfg.Type,
	}
	return redis.MustNewRedis(redisConf)
}

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	redisClient := InitRedis(c.Redis)
	fs := noDirFileSystem{fs: http.Dir("./static")}
	//fs := http.Dir("./static")
	server := rest.MustNewServer(c.RestConf, rest.WithFileServer("/static/", fs))
	defer server.Stop()

	ctx := svc.NewServiceContext(c, redisClient)
	handler.RegisterHandlers(server, ctx)
	fmt.Printf("MonUrl: %s\n", c.MonDB.Url)
	fmt.Printf("FromEmail: %s\n", c.EConf.From)
	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
